package com.eightbears.beboy;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.entity.LocalDistrictEntity;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.StaticDataEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.login.LoginActivity;
import com.eightbears.greendao.District;
import com.socks.library.KLog;

import java.util.List;

import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.URL_STATIC_DATA;

/**
 * 欢迎页面
 */
public class SplashActivity extends BaseActivity {

    private static final int FINISH_FOR_LOGIN = 1;
    private static final int FINISH_FOR_DASH = 2;
    private static final int FINISH_FOR_GUIDE = 3;
    private static final long DELAY_TIME = 1500;

    private UserEntity mUserEntity;
    private MyHandler handler;
    private StaticDataEntity staticDataEntity;
    private StaticDataEntity mStaticDataEntity;
    private AMapLocationClient mapLocationClient;
    private AMapLocationClientOption option;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        handler = new MyHandler();
        if (!isNetWorkConnected(this)) {
            handler.sendEmptyMessageDelayed(FINISH_FOR_LOGIN, DELAY_TIME);
            return;
        }


        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
        }
    }

    @Override
    protected void initData() {
        mUserEntity = SPUtil.getUser();
        mStaticDataEntity = SPUtil.getStaticData();
        checkVersion();
        initLocation();
        getStaticData();

    }

    @Override
    protected void initEvent() {

    }

    private void checkVersion() {
        try {
            int localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
            if (localVersion < 25) {
                SPUtil.clear();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取静态数据
     */
    private void getStaticData() {
        OkHttpUtils.get().url(URL_STATIC_DATA)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                staticDataEntity = GsonUtil.fromJson(response, StaticDataEntity.class);

                if (staticDataEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    SPUtil.putStaticData(staticDataEntity);

                    if (null == mStaticDataEntity || null == mStaticDataEntity.getData()) {
                        getDistrict();
                        return;
                    }


                    if (staticDataEntity.getData().getVersion().getDistrict_version()
                            != mStaticDataEntity.getData().getVersion().getDistrict_version()) {
                        getDistrict();
                        return;
                    }
                    loginEvent();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SplashActivity.this, status_error);
            }
        });
    }

    /**
     * 获取地区列表（通过数据库保存到本地）
     */
    private void getDistrict() {
        OkHttpUtils.get().url(CommonAPI.URL_DISTRICT)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                LocalDistrictEntity districtEntity = GsonUtil.fromJson(response, LocalDistrictEntity.class);
                if (districtEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    DistrictCache.getInstance(SplashActivity.this).insertAll(districtEntity.getData());
                    loginEvent();
                }
            }

            @Override
            public void onError(Call request, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SplashActivity.this, status_error);
            }
        });
    }

    private void loginEvent() {
        //发消息打开页面
        if (null == mUserEntity || null == mUserEntity.getData().getAccess_token()) {
            if (SPUtil.getAlreadyLogin())
                handler.sendEmptyMessageDelayed(FINISH_FOR_GUIDE, DELAY_TIME);
            else
                handler.sendEmptyMessageDelayed(FINISH_FOR_LOGIN, DELAY_TIME);
        } else {
            handler.sendEmptyMessageDelayed(FINISH_FOR_DASH, DELAY_TIME);
        }
    }


    /**
     * 得到请求结果后处理相应事件
     */
    private class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FINISH_FOR_LOGIN: // 用户token过期进入登录界面
                    Intent loginIntent = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                    finish();
                    break;
                case FINISH_FOR_DASH: // 用户token没有过期进入主页面
                    Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(mainIntent);
                    finish();
                    break;
                case FINISH_FOR_GUIDE:
                    Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
                    startActivity(intent);
                    finish();
                    break;
            }
        }
    }

    /**
     * 初始化定位
     */
    public void initLocation() {
        mapLocationClient = new AMapLocationClient(getApplication());
        option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mapLocationClient.setLocationOption(option);
        mapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        LocationEntity locationEntity = new LocationEntity();
                        locationEntity.setLatitude(aMapLocation.getLatitude() + "");
                        locationEntity.setLongitude(aMapLocation.getLongitude() + "");
                        locationEntity.setCityName(aMapLocation.getCity());
                        locationEntity.setHomeCityName(aMapLocation.getCity());
                        locationEntity.setDistrictName(aMapLocation.getDistrict());
                        locationEntity.setProvinceName(aMapLocation.getProvince());
                        SPUtil.putUserLocation(locationEntity);
                    } else {
                        SPUtil.putUserLocation(new LocationEntity());
                    }
                }
            }
        });
        mapLocationClient.startLocation();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != mapLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mapLocationClient.onDestroy();
            mapLocationClient = null;
            option = null;
        }
    }
}
